var lyby = require('../util');
var assign = require('object-assign');
var express = require('express');
var router = express.Router();
var fs = require("fs");
var layoutStr = 'layout';
var user_class = require('./users');
var request = require('request');
var url = require('url');
var querystring = require('querystring');

var users = require('./users');


var getRedirectParams = function (config) {
    var appsName = config.name;
    if(appsName == undefined){
        console.log('moduls name is null')
    }
    // var loginUser = req.session.userinfo;
    // var fsStr = '/develop/apps/' + appsName + '.js';
    var fsStr = __basename + '/../src/containers/' + appsName;
    if (fs.existsSync(fsStr)) {
        var hbsStr = __basename + '/views/node/apps/' + appsName + '.hbs';
        //如果有node模版用它的，没有的话走公共的
        if (fs.existsSync(hbsStr)) {
            hbsStr = 'node/apps/' + appsName;
        } else {
            hbsStr = 'node/apps/commonAPPS';
        }
        return {
            renderStr: hbsStr,
            params: {
                //登陆的用户信息
                //userInfoStr : JSON.stringify(loginUser),//global.userInfo,
                layout: 'node/master_layout',
                appsName: appsName,
                bodyHtml: lyby.getNewReactHtml(assign({
                    jsxName: appsName,
                    jsxPath: __basename + '/webpack_shijue/react_develop/',
                    jsxUrl: fsStr
                },config))
                // cur_parems_str: JSON.stringify(req.query)
            }
        }
    } else {
        return {}
    }
}
var _fn = function (req, res, next) {
    var rs =    getRedirectParams({
        name: req.params.appsName
    })
    if (rs.renderStr) {
        var loginUser = req.session.userinfo;
        // if(!loginUser){
        //     res.redirect('/user/login?redirect=/home');
        // }else{
        res.render(rs.renderStr, assign(rs.params, {
            userInfoStr: JSON.stringify(loginUser),//global.userInfo,
            cur_parems_str: JSON.stringify(req.query)
        }))
        // }
    }else{
        next();
    }
}
router.get('/m/:appsName', _fn);
router.get('/m/:appsName/*', _fn);
router.get('/n/m/:appsName', _fn);
router.get('/n/m/:appsName/*', _fn);

module.exports = router;